<?php
// +-------------------------------------------------------------------
// | 
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Kcdns\Admin\Controller;

/**
 * 属性控制器
 */
class AttributeController extends CommonController
{

    protected function _initialize ()
    {
        parent::_initialize();
        $this->listWhere = [
                'attribute.model_id' => I('get.model.id')
        ];
    }
    
    // 检测动态权限
    protected function checkDynamic ()
    {
        return is_administrator();
    }
    

    /**
     * 新增页面初始化
     */
    public function add ()
    {
        if (IS_POST)
        {
            D('Attribute')->update() ? $this->success('新增成功', U('index')) : $this->error(D('Attribute')->getError());
        }
        
        $model_id = I('get.model_id') or $this->error('参数不能为空！');
        
        $model = M('Model')->field('title,name,field_group')->find($model_id) or $this->error('模型不存在！');
        $cfgModel = getCfgModel('attribute');
        $model['fields'] = $cfgModel['fields'];
        $data = array(
                'model_id' => $model_id
        );
        
        $this->meta_title = '新增属性';
        $this->assign('model', $this->_getCfgModel($model_id));
        $this->assign('data', $data);
        $this->display('edit');
    }

    /**
     * 编辑页面初始化
     */
    public function edit ()
    {
        if (IS_POST)
        {
            D('Attribute')->update() ? $this->success('更新成功', U('index')) : $this->error(D('Attribute')->getError());
        }
        
        $id = I('get.id', '') or $this->error('参数不能为空！');
        $data = M('Attribute')->field(true)->find(I('get.id', '')) or $this->error("属性不存在！");
        
        $this->meta_title = '编辑属性';
        $this->assign('model', $this->_getCfgModel($data['model_id']));
        $this->assign('data', $data);
        $this->display();
    }

    /**
     * 删除一条数据
     */
    public function remove ()
    {
        $Model = D('Attribute');
        $id = I('id') or $this->error('参数错误！');
        $info = $Model->getById($id) or $this->error('该字段不存在！');
        
        // 删除表字段, 删除属性数据
        $res = $Model->delete($id) and $Model->deleteField($info);
        $res and action_log('update_attribute', 'attribute', $id, UID);
        $res ? $this->success('删除成功', U('index', 'model_id=' . $info['model_id'])) : $this->error(D('Attribute')->getError());
    }
}
